#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void print(int val){
    cout << val << endl;
}

class Person{
public:
    string p_name;
    int age;
    Person(string name, int age){
        this->p_name = name;
        this->age = age;
    }
};

/*
 * vector容器 类似数组
 */

// vector 存放内置数据类型
void test01(){
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);

    // 通过迭代器访问容器中的数据

    // 第一种遍历方式
    cout << "第一种" << endl;
    vector<int>::iterator itBegin = v.begin();  // 指向容器中第一个元素
    vector<int>::iterator itEnd = v.end();  // 指向容器中最后一个元素的后一个元素
    while (itBegin != itEnd){
        cout << *itBegin << endl;
        itBegin++;
    }

    // 第二种遍历方式
    cout << "第二种" << endl;
    for (vector<int>::iterator iBegin=v.begin(); iBegin < v.end(); iBegin++) {
        cout << *iBegin << endl;
        itBegin++;
    }

    // 第三种遍历方式
    cout << "第三种" << endl;
    for_each(v.begin(), v.end(), print);
}

// 存放自定义数据类型
void test02(){
    Person p1("a", 10);
    Person p2("b", 11);
    Person p3("c", 12);
    Person p4("d", 13);
    Person p5("e", 14);
    vector<Person> v;
    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);
    v.push_back(p4);
    v.push_back(p5);
    for (vector<Person>::iterator begin=v.begin(); begin < v.end(); ++begin) {
        cout << "name="<< (*begin).p_name <<", age="<<(*begin).age << endl;
    }
}

// 存放自定义数据类型指针
void test03(){
    Person p1("a", 10);
    Person p2("b", 11);
    Person p3("c", 12);
    Person p4("d", 13);
    Person p5("e", 14);
    vector<Person *> v;
    v.push_back(&p1);
    v.push_back(&p2);
    v.push_back(&p3);
    v.push_back(&p4);
    v.push_back(&p5);
    for (vector<Person *>::iterator begin=v.begin(); begin < v.end(); ++begin) {
        cout << "name="<< (*begin)->p_name <<", age="<<(*begin)->age << endl;
    }
}

// 容器嵌套容器
void test04(){
    vector<vector<int>> v;
    vector<int> v1;
    vector<int> v2;
    vector<int> v3;
    vector<int> v4;
    for (int i = 0; i < 4; ++i) {
        v1.push_back(i+1);
        v2.push_back(i+2);
        v3.push_back(i+3);
        v4.push_back(i+4);
    }
    v.push_back(v1);
    v.push_back(v2);
    v.push_back(v3);
    v.push_back(v4);
    for (vector<vector<int>>::iterator vBegin=v.begin(); vBegin < v.end(); ++vBegin) {
        for (vector<int>::iterator begin=vBegin->begin(); begin < vBegin->end(); ++begin) {
            cout << " " << *begin <<" ";
        }
        cout << endl;
    }
}

int main() {

    test01();

    test02();
    cout << "指针类型" << endl;
    test03();

    cout << "嵌套" << endl;
    test04();

    return 0;
}
